module SQS4Rails; end 

class SQS4Rails::SQSLogger
    @@queues = {}
    
    def initialize(options = {})
      self.class.setup(options) if options[:key] and options[:secret]
    end
    
    def self.new_queue(queue_name) 
      queue = SQS.get_queue(queue_name)
      if @@queues[queue_name] or queue
        if @@queues[queue_name].nil? and @@queues[queue_name]
          @@queues[queue_name] = queue
          return false
        end
        return false
      else
        return create_queue(queue_name)
      end
    rescue Exception => e
      create_queue(queue_name)
    end
    
    def new_queue(queue_name)
      self.class.new_queue(queue_name)
    end
    
    def self.setup(options = {})
      options = options["sqs"] if options["sqs"]
      options.symbolize_keys!
      SQS.access_key_id = options[:key] if options[:key]
      SQS.secret_access_key = options[:secret] if options[:secret]
      SQS.list_queues.each do |queue|
          @@queues[queue.name.to_sym] = queue
      end       
      new_queue(options[:queue_name]) if options[:queue_name]
    end

    def self.publish(queue_name, message)
      @@queues[queue_name].send_message(message.to_yaml)
    end
    
    def publish(queue_name, message)
      self.class.publish(queue_name, message)
    end
    
    def self.read(queue_name)
      message = @@queues[queue_name].receive_message
      message_body = message.body
      message.delete
      return YAML.load(message_body)
    rescue Exception => e
      puts "There was an error reading a message from SQS " << e
      false
    end
    
    def read(queue_name)
      self.class.read(queue_name)
    end
    
    def self.remove_queue(option = :all)
      if option == :all
        SQS.list_queues.each do |queue|
          queue.delete!         
        end
         @@queues = {}
      else
        @@queues[option].delete! and @@queues.delete(option) 
      end
    end
    
    def self.messages?(queue_name)
      !@@queues[queue_name].empty?
    end
    
    def messages?(queue_name)
      self.class.messages?(queue_name)
    end
    
    def remove_queue(option = :all)
      self.class.remove_queue(option)
    end
    
    
    protected
    
    
    def queue_exists?(queue_name)
      match = false
      SQS.list_queues.each do |queue|
        match = (queue.name == queue_name)
        break if match         
      end
      return match
    end

    private
    
    def self.create_queue(queue_name)
      @@queues[queue_name] = SQS.create_queue(queue_name)
    end
    
    def create_queue(queue_name)
      self.class.create_queue(queue_name)
    end
end
  
